/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import '../../base-ui/BaseElement';
import '../sub-template/SpDivItemTemp';
import { BaseElement, element } from '../../base-ui/BaseElement';
import { SpDivItemTemp } from '../sub-template/SpDivItemTemp';
import '../sub-template/SpDivChartTemp';
import '../sub-template/SpDivTableTemp';
import { SpDivChartTemp } from '../sub-template/SpDivChartTemp';
import { LitLineChart } from '../../base-ui/chart/lineChart/LitLineChart';
import { SpDivTableTemp } from '../sub-template/SpDivTableTemp';
import { SpStatisticsHttpUtil } from '../util/SpStatisticsHttpUtil';
import { conversionChartPoints } from '../util/SpStatisticsGroupUtil';
import { LitDatePicker } from '../../base-ui/datepicker/LitDatePicker';
import { GroupType } from '../util/SpStatisticsHttpBean';

@element('sp-user-statistics-panel')
export class SpUserStatisticsPanel extends BaseElement {
  private userItems: HTMLDivElement | undefined | null;
  private userChart: SpDivChartTemp | undefined | null;
  private userTable: SpDivTableTemp | undefined | null;
  private lineChart: LitLineChart | undefined | null;
  private dataPicker: LitDatePicker | undefined | null;
  private userMap: any;
  private userItemMap: any;
  private homePageInterval: any;
  private requestBody: any;

  initElements(): void {
    this.userItems = this.shadowRoot?.querySelector<HTMLDivElement>('.user-items');
    this.userChart = this.shadowRoot?.querySelector<SpDivChartTemp>('.user-chart');
    this.userTable = this.shadowRoot?.querySelector<SpDivTableTemp>('.user-table');
    this.dataPicker = this.userChart!.shadowRoot?.querySelector<LitDatePicker>('lit-datepicker');

    let startStr = SpStatisticsHttpUtil.getPreviousDate(6);
    let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startStr);
    let endTimeStr: string = SpStatisticsHttpUtil.getToday();
    let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
    let currentDay = new Date();
    let dataPickerAttr = {
      datePickerType: 'rangeDate',
      direction: 'bottomLeft',
      dateType: 'date',
      defaultDateValue: `${startStr} ~ ${endTimeStr}`,
      minDate: '2020-1-1',
      maxDate: `${currentDay.getFullYear()}-${currentDay.getMonth() + 1}-${currentDay.getDate()}`,
    };
    this.requestBody = {
      startTime: startTime,
      endTime: endTime,
      interval: SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime),
    };
    this.userMap = {
      addUSer: '新增用户',
      activeUser: '活跃用户',
      access: '访问次数',
      totalUser: '累计用户',
    };

    this.userItemMap = {
      addUser: '-',
      sevenDayUser: '-',
      mouthDayUser: '-',
      allUser: '-',
      sevenDayAccess: '-',
      mouthDayAccess: '-',
      allAccess: '-',
      traceAnalysisAccess: '-'
    };
    this.initHomePageUserItem(dataPickerAttr);
    this.initHomePageUserChart();
    if (this.dataPicker) {
      this.dataPicker!.addEventListener('date_change', (ev: any) => {
        let detail = ev.detail;
        let startTimeStr = detail.startTime;
        let endTimeStr = detail.endTime;
        let startTs: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
        let endTs: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
        this.requestBody = {
          startTime: startTs,
          endTime: endTs,
          interval: SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTs, endTs),
        };
        this.resetHomePageData(this.requestBody);
      });
    }
  }

  refreshHomePage() {
    this.resetHomePageData(this.requestBody);
  }

  resetHomePageData(requestBody: any) {
    let homePageChartTableCallBack = (homepageData: any) => {
      let chartData = conversionChartPoints(requestBody, homepageData.data);
      chartData['totalUser'].reduce((pre: any, item: any) => {
        item.value += pre ? pre.value : 0;
        return item;
      });
      if (this.lineChart) {
        this.lineChart.dataSource(chartData, this.userMap);
      }
      this.resetHomeTable(homepageData, chartData);
    };
    SpStatisticsHttpUtil.getUserVisitData('homepageChart', homePageChartTableCallBack, requestBody);
  }

  resetHomeTable(homepageData: any, chartData: any) {
    if (this.userTable) {
      let activeUsers: Array<any> = [];
      if (homepageData.data['activeUser']) {
        homepageData.data['activeUser'].forEach((activeUser: any) => {
          if (activeUsers.length === 0) {
            activeUsers.push(activeUser['userId']);
          } else {
            if (activeUsers.indexOf(activeUser['userId']) < 0) {
              activeUsers.push(activeUser['userId']);
            }
          }
        })
      }
      let resultData = this.transformTableData(chartData);
      if (resultData.length > 1) {
        resultData[0]['累计用户'] = Math.max.apply(
          Math,
          chartData['totalUser'].map((chart: any) => chart.value)
        );
        resultData[0]['活跃用户'] = '-';
      } else {
        resultData[0]['访问次数'] = 0;
        resultData[0]['活跃用户'] = 0;
        resultData[0]['新增用户'] = 0;
        resultData[0]['累计用户'] = 0;
      }
      this.userTable!.dataSource(resultData);
    }
  }

  initHomePageUserItem(dataPickerAttr: any) {
    // 没数据的时候先让展示出来，默认展示初始值0
    this.getStatisticsItems().forEach((item) => {
      let itemDivEl = new SpDivItemTemp();
      itemDivEl.setAttribute('title', item.title);
      itemDivEl.setAttribute('icon', item.icon);
      itemDivEl.setAttribute('data', item.data);
      itemDivEl.setAttribute('id', '')
      itemDivEl.className = 'user-item';
      this.userItems!.appendChild(itemDivEl);
    });
    let params = {
      startTime: new Date('2023-01-01T00:00:00Z').getTime(),
      endTime: new Date().getTime(),
      interval: GroupType.DAY,
    }
    SpStatisticsHttpUtil.getOrdinaryVisitData('importTrace', params, (res: any) => {
      let traceAnalysisAccess: number = 0;
      if (res.code === 0 && res.data.importTrace && res.data.importTrace.length > 0) {
        res.data.importTrace.map((v: any) => {
          traceAnalysisAccess += v.value;
        })
      }
      let divEL = document.querySelector("body > sp-statistics-application")!
        .shadowRoot!.querySelector("#user-root-statistics")!.shadowRoot!
        .querySelector("div > div.user-content > div.user-items")!.querySelector('[title = "trace解析总量"]');
      divEL?.setAttribute('data', traceAnalysisAccess.toString());
    })
    let homePageDataCallBack = (homepageData: any) => {
      this.getStatisticsItems(homepageData).slice(0, 7).forEach((item) => {
        let divEL = document.querySelector("body > sp-statistics-application")!
          .shadowRoot!.querySelector("#user-root-statistics")!.shadowRoot!
          .querySelector("div > div.user-content > div.user-items")!.querySelector(`[title = "${item.title}"]`);
        divEL!.setAttribute('data', item.data === '-' ? '0' : item.data);
      });
      if (this.userChart) {
        this.userChart.tabsData(this.userMap);
        this.userChart.timeData(dataPickerAttr);
      }
    };
    SpStatisticsHttpUtil.getUserVisitData('homePage', homePageDataCallBack);
  }

  initHomePageUserChart() {
    let homePageChartDataCallBack = (homepageData: any) => {
      let chartData = conversionChartPoints(this.requestBody, homepageData.data);
      chartData['totalUser'].reduce((pre: any, item: any) => {
        item.value += pre ? pre.value : 0;
        return item;
      });
      this.lineChart = new LitLineChart();
      this.lineChart.dataSource(chartData, this.userMap);
      this.lineChart.style.height = '400px';
      this.userChart!.chartData(this.lineChart);
      this.userChart!.addEventListener('switch-change', (evt) => {
        // @ts-ignore
        let data = evt.detail.value;
        // @ts-ignore
        let color = evt.detail.color;
        this.lineChart!.filterData(data, color);
      });
      this.resetHomeTable(homepageData, chartData);
    };
    SpStatisticsHttpUtil.getUserVisitData('homepageChart', homePageChartDataCallBack, this.requestBody);
  }

  transformTableData(chartData: any) {
    let resultData: any = [];
    Object.keys(chartData).forEach((item) => {
      let totalValue = 0;
      let headName = this.userMap[item];
      chartData[item].forEach((row: any, index: number) => {
        if (index === 0) {
          if (resultData[index] === undefined) {
            resultData.push({
              日期: '',
            });
            resultData.push({
              日期: row.date,
            });
          }
          resultData[index + 1][headName] = row.value;
          totalValue += row.value;
        } else {
          if (resultData[index + 1] === undefined) {
            resultData.push({
              日期: row.date,
            });
          }
          resultData[index + 1][headName] = row.value;
          totalValue += row.value;
          if (index === chartData[item].length - 1) {
            resultData[0][headName] = totalValue;
          }
        }
      });
    });
    return resultData;
  }

  getStatisticsItems(homepageData?: any): Array<StatisticsItems> {
    if (homepageData && homepageData.msg === 'success') {
      if (homepageData.data.length > 0) {
        homepageData.data.forEach((it: any) => {
          this.userItemMap[it.key] = it.value;
        });
      }
    }
    let defaultData: Array<string> = Object.values(this.userItemMap);
    return [
      {
        icon: 'user-add',
        title: '新增用户',
        description: '新增用户',
        data: defaultData[0],
      },
      {
        icon: 'seven-add',
        title: '近7日总活跃用户数',
        description: '活跃用户',
        data: defaultData[1],
      },
      {
        icon: 'thirty-add',
        title: '近30日总活跃用户数',
        description: '新增用户',
        data: defaultData[2],
      },
      {
        icon: 'total-users',
        title: '累计用户数',
        description: '新增用户',
        data: defaultData[3],
      },
      {
        icon: 'seven-visit',
        title: '7日访问量',
        description: '新增用户',
        data: defaultData[4],
      },
      {
        icon: 'thirty-visit',
        title: '30日访问量',
        description: '新增用户',
        data: defaultData[5],
      },
      {
        icon: 'total-visit',
        title: '累计访问量',
        description: '新增用户',
        data: defaultData[6],
      },
      {
        icon: 'statistics',
        title: 'trace解析总量',
        description: '新增用户',
        data: defaultData[7],
      },
    ];
  }

  clearStatisticsPanel() {
    if (this.dataPicker) {
      this.dataPicker.clearDatePickerContent();
    }
    clearInterval(this.homePageInterval);
  }

  initHtml(): string {
    return `<style>
        :host{
    
        }
        .user-panel {
            width: 100%;
            height: 100%;
        }
        .user-content {
            width: 100%;
            height: 100%;
        }
        .user-items {
            display: flex;    
            flex-wrap: wrap;
            padding: 1% 2%;
            justify-content: space-between;
        }
        .user-charts {
            padding: 1% 2%;
        }
        .user-item {
            display: flex;
            width: 12%;
            height: 200px;
            border: 0;        
        }
        .user-tables {
            display: flex;
            padding: 2% 2%;  
        }
        .user-table {
            height: 50vh;
            width: 100%;
        }
        </style>
        <div class="user-panel">
            <div class="user-head"></div>
            <div class="user-content">
                 <div class="user-items"></div>
                 <div class="user-charts">
                    <sp-div-chart-temp class="user-chart"></sp-div-chart-temp>
                </div>
                <div class="user-tables">
                    <sp-div-table-temp class="user-table"></sp-div-table-temp>
                </div>
            </div>
        </div>
        `;
  }
}

export interface StatisticsItems {
  icon: string;
  title: string;
  description: string;
  data: string;
}
